/**
 * API服务模块
 * 处理与后端API的通信
 */

/**
 * API响应格式
 */
interface ApiResponse<T = any> {
  success: boolean;
  data: T;
  message: string;
  timestamp: string;
}

/**
 * 后端RSS源数据格式
 */
interface BackendRSSFeed {
  id: number;
  title: string;
  url: string;
  description?: string;
  createdAt: string;
  lastUpdated: string;
  unreadCount: number;
}

/**
 * 后端文章数据格式
 */
interface BackendArticle {
  id: number;
  feedId: number;
  title: string;
  summary?: string;
  content?: string;
  link: string;
  publishedAt: string;
  author?: string;
  imageUrl?: string;
  isRead: boolean;
  isFavorite: boolean;
  createdAt: string;
}

/**
 * 分页查询参数
 */
interface PageQuery {
  page?: number;
  size?: number;
  keyword?: string;
  feedId?: number;
  unreadOnly?: boolean;
  favoriteOnly?: boolean;
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
}

/**
 * 分页响应数据
 */
interface PageResponse<T> {
  content: T[];
  totalElements: number;
  totalPages: number;
  size: number;
  number: number;
  first: boolean;
  last: boolean;
}

/**
 * API基础配置
 */
const API_BASE_URL = '/api';

/**
 * 通用请求函数
 */
async function request<T = any>(
  url: string,
  options: RequestInit = {}
): Promise<ApiResponse<T>> {
  try {
    const response = await fetch(`${API_BASE_URL}${url}`, {
      headers: {
        'Content-Type': 'application/json',
        ...options.headers,
      },
      ...options,
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    const data = await response.json();
    return data;
  } catch (error) {
    console.error('API请求失败:', error);
    throw error;
  }
}

/**
 * RSS源相关API
 */
export const feedsApi = {
  /**
   * 获取RSS源列表
   */
  async getFeeds(): Promise<ApiResponse<PageResponse<BackendRSSFeed>>> {
    return request<PageResponse<BackendRSSFeed>>('/feeds');
  },

  /**
   * 添加RSS源
   */
  async addFeed(feedData: {
    title: string;
    url: string;
    description?: string;
    link?: string;
  }): Promise<ApiResponse<BackendRSSFeed>> {
    return request<BackendRSSFeed>('/feeds', {
      method: 'POST',
      body: JSON.stringify(feedData),
    });
  },

  /**
   * 更新RSS源
   */
  async updateFeed(
    id: number,
    feedData: Partial<{
      title: string;
      url: string;
      description: string;
      link: string;
      isActive: boolean;
    }>
  ): Promise<ApiResponse<BackendRSSFeed>> {
    return request<BackendRSSFeed>(`/feeds/${id}`, {
      method: 'PUT',
      body: JSON.stringify(feedData),
    });
  },

  /**
   * 删除RSS源
   */
  async deleteFeed(id: number): Promise<ApiResponse<void>> {
    return request<void>(`/feeds/${id}`, {
      method: 'DELETE',
    });
  },

  /**
   * 刷新RSS源
   */
  async refreshFeed(id: number): Promise<ApiResponse<void>> {
    return request<void>(`/feeds/${id}/refresh`, {
      method: 'POST',
    });
  },

  /**
   * 刷新所有RSS源
   */
  async refreshAllFeeds(): Promise<ApiResponse<void>> {
    return request<void>('/feeds/refresh-all', {
      method: 'POST',
    });
  },

  /**
   * 验证RSS源URL
   */
  async validateFeed(url: string): Promise<ApiResponse<{ valid: boolean; title?: string; description?: string }>> {
    return request<{ valid: boolean; title?: string; description?: string }>('/feeds/validate', {
      method: 'POST',
      body: JSON.stringify({ url }),
    });
  },
};

/**
 * 文章相关API
 */
export const articlesApi = {
  /**
   * 获取文章列表（分页）
   */
  async getArticles(params: PageQuery = {}): Promise<ApiResponse<PageResponse<BackendArticle>>> {
    const searchParams = new URLSearchParams();
    
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== null) {
        searchParams.append(key, String(value));
      }
    });

    const queryString = searchParams.toString();
    const url = queryString ? `/articles?${queryString}` : '/articles';
    
    return request<PageResponse<BackendArticle>>(url);
  },

  /**
   * 获取文章详情
   */
  async getArticle(id: number): Promise<ApiResponse<BackendArticle>> {
    return request<BackendArticle>(`/articles/${id}`);
  },

  /**
   * 标记文章为已读
   */
  async markAsRead(id: number): Promise<ApiResponse<void>> {
    return request<void>(`/articles/${id}/read`, {
      method: 'POST',
    });
  },

  /**
   * 标记文章为未读
   */
  async markAsUnread(id: number): Promise<ApiResponse<void>> {
    return request<void>(`/articles/${id}/unread`, {
      method: 'POST',
    });
  },

  /**
   * 批量标记文章为已读
   */
  async batchMarkAsRead(articleIds: number[]): Promise<ApiResponse<void>> {
    return request<void>('/articles/batch-read', {
      method: 'POST',
      body: JSON.stringify({ articleIds }),
    });
  },

  /**
   * 标记RSS源下所有文章为已读
   */
  async markFeedAsRead(feedId: number): Promise<ApiResponse<void>> {
    return request<void>(`/articles/feeds/${feedId}/read-all`, {
      method: 'POST',
    });
  },

  /**
   * 搜索文章
   */
  async searchArticles(params: {
    keyword: string;
    page?: number;
    size?: number;
    feedId?: number;
  }): Promise<ApiResponse<PageResponse<BackendArticle>>> {
    const searchParams = new URLSearchParams();
    
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== null) {
        searchParams.append(key, String(value));
      }
    });

    return request<PageResponse<BackendArticle>>(`/articles/search?${searchParams.toString()}`);
  },

  /**
   * 获取未读文章数量
   */
  async getUnreadCount(): Promise<ApiResponse<{ count: number }>> {
    return request<{ count: number }>('/articles/unread-count');
  },

  /**
   * 获取最新文章
   */
  async getLatestArticles(limit: number = 10): Promise<ApiResponse<BackendArticle[]>> {
    return request<BackendArticle[]>(`/articles/latest?limit=${limit}`);
  },

  /**
   * 删除文章
   */
  async deleteArticle(id: number): Promise<ApiResponse<void>> {
    return request<void>(`/articles/${id}`, {
      method: 'DELETE',
    });
  },

  /**
   * 批量删除文章
   */
  async batchDeleteArticles(articleIds: number[]): Promise<ApiResponse<void>> {
    return request<void>('/articles/batch', {
      method: 'DELETE',
      body: JSON.stringify({ articleIds }),
    });
  },

  /**
   * 清理旧文章
   */
  async cleanOldArticles(days: number = 30): Promise<ApiResponse<{ deletedCount: number }>> {
    return request<{ deletedCount: number }>(`/articles/clean?days=${days}`, {
      method: 'DELETE',
    });
  },

  /**
   * 获取文章统计信息
   */
  async getStatistics(): Promise<ApiResponse<{
    totalArticles: number;
    unreadArticles: number;
    favoriteArticles: number;
    todayArticles: number;
  }>> {
    return request<{
      totalArticles: number;
      unreadArticles: number;
      favoriteArticles: number;
      todayArticles: number;
    }>('/articles/statistics');
  },

  /**
   * 标记所有文章为已读
   */
  async markAllAsRead(): Promise<ApiResponse<void>> {
    return request<void>('/articles/read-all', {
      method: 'POST',
    });
  },

  /**
   * 收藏文章
   * @param {number} id - 文章ID
   * @returns {Promise<ApiResponse<void>>} API响应
   */
  async favoriteArticle(id: number): Promise<ApiResponse<void>> {
    return request<void>(`/articles/${id}/favorite`, {
      method: 'POST',
    });
  },

  /**
   * 取消收藏文章
   * @param {number} id - 文章ID
   * @returns {Promise<ApiResponse<void>>} API响应
   */
  async unfavoriteArticle(id: number): Promise<ApiResponse<void>> {
    return request<void>(`/articles/${id}/unfavorite`, {
      method: 'POST',
    });
  },

  /**
   * 切换文章收藏状态
   * @param {number} id - 文章ID
   * @param {boolean} isFavorite - 当前收藏状态
   * @returns {Promise<ApiResponse<void>>} API响应
   */
  async toggleFavorite(id: number, isFavorite: boolean): Promise<ApiResponse<void>> {
    if (isFavorite) {
      return this.unfavoriteArticle(id);
    } else {
      return this.favoriteArticle(id);
    }
  },
};

/**
 * 数据转换工具
 */
export const dataTransform = {
  /**
   * 将后端RSS源数据转换为前端格式
   */
  backendFeedToFrontend(backendFeed: BackendRSSFeed): any {
    return {
      id: backendFeed.id.toString(),
      title: backendFeed.title,
      url: backendFeed.url,
      description: backendFeed.description || '',
      link: '', // 后端暂时没有返回link字段
      favicon: `https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=${encodeURIComponent(backendFeed.title + ' logo icon')}&image_size=square`,
      categoryId: 'default', // 后端暂时没有分类功能
      isActive: true, // 后端暂时没有返回isActive字段，默认为true
      createdAt: new Date(backendFeed.createdAt),
      updatedAt: new Date(backendFeed.lastUpdated),
      articleCount: 0, // 后端暂时没有返回articleCount字段，默认为0
      unreadCount: backendFeed.unreadCount,
    };
  },

  /**
   * 将后端文章数据转换为前端格式
   * @param {any} backendArticle - 后端文章数据
   * @returns {any} 前端格式的文章数据
   * @throws {Error} 当必要字段缺失时抛出错误
   */
  backendArticleToFrontend(backendArticle: any): any {
    // 验证必要字段
    if (!backendArticle) {
      console.error('❌ backendArticle is null or undefined');
      throw new Error('文章数据为空');
    }
    
    if (backendArticle.id === undefined || backendArticle.id === null) {
      console.error('❌ backendArticle.id is missing:', backendArticle);
      throw new Error('文章ID缺失');
    }
    
    if (!backendArticle.title) {
      console.error('❌ backendArticle.title is missing:', backendArticle);
      throw new Error('文章标题缺失');
    }
    
    try {
      // 安全的标题处理，用于生成图片URL
      const safeTitle = (backendArticle.title || '默认标题').substring(0, 50);
      
      // 从feed对象中获取feedId，如果没有feed对象则使用feedId字段
      let feedId = '';
      if (backendArticle.feed && backendArticle.feed.id) {
        feedId = backendArticle.feed.id.toString();
      } else if (backendArticle.feedId) {
        feedId = backendArticle.feedId.toString();
      } else {
        console.warn('⚠️ 文章缺少RSS源ID信息:', backendArticle);
        feedId = 'unknown';
      }
      
      return {
        id: backendArticle.id.toString(),
        feedId: feedId,
        title: backendArticle.title,
        summary: backendArticle.description || backendArticle.summary || '',
        content: backendArticle.content || '',
        link: backendArticle.link || '',
        publishedAt: backendArticle.publishedAt ? new Date(backendArticle.publishedAt) : new Date(),
        author: backendArticle.author || '',
        isRead: Boolean(backendArticle.isRead),
        isFavorite: Boolean(backendArticle.isFavorite || false),
        tags: [], // 后端暂时没有标签功能
        imageUrl: backendArticle.imageUrl || `https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=${encodeURIComponent(safeTitle)}&image_size=landscape_4_3`,
        createdAt: backendArticle.createdAt ? new Date(backendArticle.createdAt) : new Date(),
      };
    } catch (error) {
      console.error('❌ 文章数据转换失败:', error, backendArticle);
      throw new Error(`文章数据转换失败: ${error.message}`);
    }
  },

  /**
   * 将前端RSS源数据转换为后端格式
   */
  frontendFeedToBackend(frontendFeed: any): Partial<BackendRSSFeed> {
    return {
      title: frontendFeed.title,
      url: frontendFeed.url,
      description: frontendFeed.description,
      link: frontendFeed.link,
      isActive: frontendFeed.isActive,
    };
  },
};